package com.heima.admin.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.UserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author lo
 * @date 2021/9/20
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(UserDto userDto) {
        //1.校验参数
        if (Strings.isBlank(userDto.getName()) || Strings.isBlank(userDto.getPassword())) {
            //参数不能为空
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "用户名或密码不能为空");
        }

        //2.根据用户名查询数据
        AdUser user = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, userDto.getName()));

        //3.判断用户数据
        if (user == null) {
            //说明没用查询到数据
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户名或者密码错误");
        }
        //4.判断用户状态 如果是9 就是正常
        if (!user.getStatus().equals(AdminConstants.USER_STATUS_NORMAL)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }

        //5.校验密码
        String password = user.getPassword();
        String salt = user.getSalt();

        //将传递过来的密码加盐再加密 进行判断
        String md5Password = DigestUtils.md5DigestAsHex((userDto.getPassword() + salt).getBytes());

        if (!md5Password.equals(password)) {
            //密码不正确
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //修改登录时间
        user.setLoginTime(new Date());

        //根据用户id颁发token
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));

        //创建返回对象
        AdUserVO userVO = new AdUserVO();
        BeanUtils.copyProperties(user, userVO);
        //封装数据并返回
        Map<Object, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", userVO);
        return ResponseResult.okResult(map);
    }
}
